<template>
  <Others ref="otherRef" :tableOpts="tableOpts" v-bind="$attrs">
    <template #addAuth="bind">
      <div class="grid grid-cols-3 gap-x-3">
        <el-form-item label="店铺名称" prop="shop_name" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="bind.form.shop_name" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="站点" prop="site_id" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VSelect v-model="bind.form.site_id" placeholder="请选择" :platform_id="$attrs.platform_id" :options="bind.options.site" :disabled="!!bind.form.shop_id" class="w-full" />
        </el-form-item>
        <el-form-item label="店铺类型" prop="shop_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="bind.form.shop_type" placeholder="请选择" :options="bind.options.shop_type" class="w-full" />
        </el-form-item>
        <el-form-item label="默认品牌" prop="saihe_shop_id">
          <VSelect v-model="bind.form.brand_ids" placeholder="请选择" :options="bind.options.brand" multiple collapse-tags class="w-full" />
        </el-form-item>
        <div class="grid grid-cols-4 gap-x-3 col-span-full">
          <Status v-model="bind.form" :options="bind.options" />
        </div>
      </div>
      <div class="v-title my-3" v-dom-load="() => loadAuth(bind)">API授权信息</div>
      <VSelect v-model="bind.form.cur_ad_id" placeholder="请选择开发者" :options="bind.options.developer" :clearable="false" class="w-60" @change="() => adChange(bind)" />
      <div v-for="(d, i) in bind.form.auths || []" :key="i" class="flex gap-3 mt-3">
        <el-form-item :prop="['auths', i, 'checked']" :rules="[{ validator: (rule, val, cb) => validator(rule, val, cb, bind.form.auths), trigger: 'change' }]">
          <el-checkbox v-if="bind.form.shop_id" :model-value="true" :disabled="true" :validate-event="false" class="w-20">{{codeMap[d.region_code]}}</el-checkbox>
          <el-checkbox v-else v-model="d.checked" :disabled="d.region_code === 'CN' || !!bind.form.shop_id" :validate-event="false"
            class="w-20">{{codeMap[d.region_code]}}</el-checkbox>
        </el-form-item>
        <el-form-item :prop="['auths', i, 'access_token']" :rules="[{ required: !!d.checked, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="d.access_token" placeholder="请输入区域token" :maxlength="200" class="w-60" />
        </el-form-item>
        <div class="leading-8">剩余天数</div>
        <el-form-item :prop="['auths', i, 'expiration_day']" :rules="[{ required: !!d.checked, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="d.expiration_day" :controls="false" :min="-9999" :precision="0" placeholder="请输入" class="w-24" @change="val => dayChange(val, d)" />
        </el-form-item>
        <template v-if="d.expiration_day !== null">
          <div v-if="d.expiration_day < 0" class="leading-8 text-red-600">已过期 截止时间：{{ getDay(d.expiration_day) }}</div>
          <div v-else-if="d.expiration_day < 15" class="leading-8 text-yellow-600">即将过期 截止时间：{{ getDay(d.expiration_day) }}</div>
          <div v-else class="leading-8">截止时间：{{ getDay(d.expiration_day) }}</div>
        </template>
      </div>
    </template>
    <template #default="{options}">
      <Auth ref="authRef" :options="options" @succuss="query" />
    </template>
  </Others>
</template>

<script lang="jsx" setup>
import Others from '../others'
import Status from '../../Status'
import XEUtils from 'xe-utils'
import { spanMethod } from '@/utils'
import Auth from './Auth'

const otherRef = ref()
const query = () => {
  otherRef?.value.query()
}

const codeMap = ref({})
const loadAuth = (bind) => {
  codeMap.value = bind.options.region_code.reduce((acc, cur) => {
    acc[cur.value] = cur.label
    return acc
  }, {})
}

const adChange = (bind) => {
  bind.form.auths.forEach(d => {
    d.access_token = ''
    d.expiration_day = null
  })
}

const getDay = val => {
  if(val === undefined) return undefined
  return XEUtils.toDateString(XEUtils.getWhatDay(Date.now(), val), 'yyyy-MM-dd')
}

const dayChange = (val, d) => {
  if(val < 0 || !val) {
    d.expiration_day = 1
  }
}

const validator = (rule, val, cb, auths) => {
  if(auths.filter(d => d.checked)?.length < 2 && !val) {
    return cb(new Error('必选一个'))
  }
  cb()
}

const authRef = ref()
const tableOpts = reactive({
  border: true,
  spanMethod: ags => spanMethod({...ags, fields: ['platform_account_name']}),
  columns: [
    { type: 'checkbox', fixed: 'left', width: 50 },
    { title: '账号名称', field: 'platform_account_name', minWidth: 140, slots: {
        default: ({ row }) => <div>
          <VText value={row.platform_account_name} line={3} />
          <VText value='更新授权' type='button' onClick={() => authRef.value.open(row.platform_account_name)} />
        </div>
      }
    },
    {
      title: '店铺账号', minWidth: 180, slots: {
        default: ({ row }) => <div>
          <VText title='店铺名称' value={row.shop_name} />
          <VText title='授权区域' value={row.auth_area} />
          <VText value={row.basic_info.shop_type} />
        </div>
      }
    },
    {
      title: '分配信息', minWidth: 160, slots: {
        default: ({ row }) => <div>
          <VText title='一级部门' value={row.alloc_info.first_level_department} />
          <VText title='二级部门' value={row.alloc_info.second_level_department} />
          <VText title='首选业务员' value={row.alloc_info.preferred_saleman_name} />
          {/* <VText title='首要客服' value={row.alloc_info.preferred_customer_service_name} /> */}
          <VText title='业务员' value={row.alloc_info.saleman_name} line='2' />
        </div>
      }
    },
    {
      title: '状态', minWidth: 80, slots: {
        default: ({ row }) => <VStatus status={row.status === '启用'} />
      }
    },
    {
      title: '授权状态', field: 'auths', minWidth: 120, slots: {
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
          {{
            default: (line) => (row.auths || []).map(d => <div class='w-full'>
              <VStatus status={row.auth_desc === '已授权'} auth />
              <VText title='授权区域' value={d.region_name} />
              <VText title='过期日期' value={getDay(d.expiration_day)} />
              <VText title='剩余' value={d.expiration_day} />
            </div>)
          }}
        </VMore>
      }
    }
  ]
})
</script>